package perm

import (
	"net/http"
	"sync"

	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

var ErrForbidden = echo.NewHTTPError(http.StatusForbidden)

// Resources permission
type Perm struct {
	sync.RWMutex
	ResPerm map[string]int
}

func New(tokenContextKey string, resPerm map[string]int) echo.MiddlewareFunc {
	p := &Perm{
		ResPerm: resPerm,
	}

	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			p.RLock()
			bits := p.ResPerm[c.Request().Method()+c.Path()]
			p.RUnlock()

			token := c.Get(tokenContextKey).(*jwt.Token)

			group := int(token.Claims["group"].(float64))

			if group&bits > 0 {
				return next(c)
			} else {
				return ErrForbidden
			}
		}
	}
}
